package com.dianziq.im.server;

public class Message {

	String content;

	int fromUID;
	int toUID;
	MsgType type;
 

	static enum MsgType {
		Default,//0聊天消息
		Control//控制消息 
		

	}
	static final Message HEARTBEAT=new Message("0",-1,MsgType.Control);


	public Message(){}
	public Message(String content,int from,MsgType type){
		this.content=content;
		this.fromUID=from;
		this.type=type;
	}
	public String toString(int id) {
		StringBuilder sb = new StringBuilder();
		sb.append("{")
			.append( ("from")).append(":").append(this.fromUID).append(",")
			.append( ("to")).append(":").append(this.toUID).append(",")
			
			.append( ("content")).append(":").append(
					this.type==MsgType.Default? quote(this.content):this.content)
				.append(",").append( ("id")).append(":")				
				.append(id)				
				.append(",").append( ("type"))
				.append(":").append(this.type.ordinal()).append("}");

		return sb.toString();

	}

	public static String quote(String string) {

		if (string == null || string.length() == 0) {
			return "\"\"";
		}

		char b;
		char c = 0;
		int i;
		int len = string.length();
		StringBuffer sb = new StringBuffer(len * 2);
		String t;
		char[] chars = string.toCharArray();
		char[] buffer = new char[1030];
		int bufferIndex = 0;
		sb.append('"');
		for (i = 0; i < len; i += 1) {
			if (bufferIndex > 1024) {
				sb.append(buffer, 0, bufferIndex);
				bufferIndex = 0;
			}
			b = c;
			c = chars[i];
			switch (c) {
			case '\\':
			case '"':
				buffer[bufferIndex++] = '\\';
				buffer[bufferIndex++] = c;
				break;
			case '/':
				if (b == '<') {
					buffer[bufferIndex++] = '\\';
				}
				buffer[bufferIndex++] = c;
				break;
			default:
				if (c < ' ') {
					switch (c) {
					case '\b':
						buffer[bufferIndex++] = '\\';
						buffer[bufferIndex++] = 'b';
						break;
					case '\t':
						buffer[bufferIndex++] = '\\';
						buffer[bufferIndex++] = 't';
						break;
					case '\n':
						buffer[bufferIndex++] = '\\';
						buffer[bufferIndex++] = 'n';
						break;
					case '\f':
						buffer[bufferIndex++] = '\\';
						buffer[bufferIndex++] = 'f';
						break;
					case '\r':
						buffer[bufferIndex++] = '\\';
						buffer[bufferIndex++] = 'r';
						break;
					default:
						t = "000" + Integer.toHexString(c);
						int tLength = t.length();
						buffer[bufferIndex++] = '\\';
						buffer[bufferIndex++] = 'u';
						buffer[bufferIndex++] = t.charAt(tLength - 4);
						buffer[bufferIndex++] = t.charAt(tLength - 3);
						buffer[bufferIndex++] = t.charAt(tLength - 2);
						buffer[bufferIndex++] = t.charAt(tLength - 1);
					}
				} else {
					buffer[bufferIndex++] = c;
				}
			}
		}
		sb.append(buffer, 0, bufferIndex);
		sb.append('"');
		return sb.toString();
	}
}
